package com.lee.service;

import com.google.common.collect.Lists;
import com.lee.domain.Employee;
import com.lee.domain.Role;
import com.lee.repository.EmployeeRepository;
import com.lee.vo.EmployeeAuthInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lee HN
 * @date 2019/6/21 15:15
 */
@Service
public class EmployeeDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Employee employee = employeeRepository.findByUsernameForAuth(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        List<Role> roleList = employee.getRoleList();
        List<GrantedAuthority> authorityList = Lists.newLinkedList();
        roleList.stream().peek(authorityList::add).map(Role::getAuthorityList).forEach(authorityList::addAll);
        String deptPath = employee.getDepartment() == null ? null : employee.getDepartment().getRootPath();
        return EmployeeAuthInfo.of(employee.getId(), employee.getUsername(), employee.getPassword(), employee.getStatus(), deptPath, authorityList);
    }


}
